package com.proxy.server.dao;

import com.proxy.common.cache.Cache;
import com.proxy.common.cache.CacheManager;
import com.proxy.common.cache.memory.MemoryCacheManager;
import com.proxy.common.entity.LocalPort;
import com.proxy.common.entity.ProxyRealServer;
import com.proxy.common.protocol.CommonConstant;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 本地端口绑定 具体操作层
 * @author ztgreat
 */
public class LocalPortBindDao {

    private static Logger logger = LoggerFactory.getLogger(LocalPortBindDao.class);

    private static CacheManager<Integer,LocalPort> cacheManager =new MemoryCacheManager<Integer,LocalPort>();

    private static Cache<Integer,LocalPort> localPortMap = cacheManager.getCache("proxy_cache");

    /**
     * 绑定服务端口
     * @param serverPort 服务器 服务端口
     * @param bootstrap 启动器
     * @throws InterruptedException
     */
    public void bind(final Integer serverPort,final ServerBootstrap bootstrap,ProxyRealServer proxyRealServer) throws InterruptedException {

        bootstrap.bind(serverPort).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture channelFuture) throws Exception {

                if (channelFuture.isSuccess()){
                    logger.info("绑定本地服务端口({})成功 客户端({})--{}",serverPort,proxyRealServer.getClientKey(),proxyRealServer.getDescription());
                    //绑定成功
                    LocalPort localPort=new LocalPort();
                    localPort.setPort(serverPort);
                    localPort.setChannel(channelFuture.channel());
                    localPort.setBootstrap(bootstrap);

                    localPort.setClientKey(proxyRealServer.getClientKey());

                    localPortMap.put(serverPort,localPort);

                    //设置状态
                    proxyRealServer.setStatus(CommonConstant.ProxyStatus.ONLINE);

                }
                else {
                    logger.info("绑定本地服务端口{}失败",serverPort);
                }

            }
        });

    }

    /**
     * 解绑 服务器端口
     * @param serverPort 需要解绑的端口
     * @return
     */
    public  boolean unBind(Integer serverPort){
        if (serverPort==null)
            return false;
        LocalPort localPort = localPortMap.get(serverPort);
        if (localPort==null)
            return false;
        localPort.getChannel().close();
        //不移除
//        localPortMap.remove(serverPort);
        return  true;


    }

    /**
     * 根据服务端口,返回绑定信息
     * @param serverPort
     * @return
     */
    public LocalPort get(Integer serverPort){
        return localPortMap.get(serverPort);
    }


}
